package com.caipiao.crawler.shengfucang;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caipiao.constant.CrawlerConstants;
import com.caipiao.crawler.mapper.LotteryFootballMapper;
import com.caipiao.crawler.model.DaletouResultModel;
import com.caipiao.crawler.model.LotteryFootball;
import com.caipiao.crawler.model.LotteryNumber;
import com.caipiao.crawler.model.Shengfc14ResultModel;
import com.caipiao.crawler.page.BasePageProcessor;
import com.caipiao.util.DBTools;
import org.apache.ibatis.session.SqlSession;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.ResultItems;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by adminitrator on 2018/7/28.
 */
public class ShengfucangResultPage extends BasePageProcessor {

    SqlSession session = DBTools.getSession();
    LotteryFootballMapper mapper = session.getMapper(LotteryFootballMapper.class);

    @Override
    public void process(Page page) {
        String url = page.getUrl().toString();
        System.out.println(url);
        if(url.contains("history")) {
            //历史页面,获取id
            processHistory(page);
        }else if(url.contains("get_typeBytermList")){
            //比赛数据
            processNowMatchTerm(page);
        }else if(url.contains("match_data")){
            processMatch(page);
        } else {
            //处理接口数据
            processData(page);
        }
    }

    public void processData(Page page) {
        String data = page.getJson().get();
        JSONObject obj = (JSONObject) ((JSONArray) JSON.parse(data)).get(0);
        JSONObject lottery = obj.getJSONObject("lottery");
        LotteryNumber model = new LotteryNumber();
        model.setPrize_detail(obj.getString("details"));
        model.setTerm(lottery.getString("term"));
        model.setNumber(lottery.getString("number"));
//        model.setDetails(obj.getString("matchResults"));
        model.setUpdated_time((int) (System.currentTimeMillis()/1000L));
        model.setType(4);
        page.putField("model", model);
    }

    public void processHistory(Page page) {
        page.setSkip(true);  //不需要传到pipeline
        String id = page.getHtml().xpath("//div[@class='result']/table/tbody/tr/td[1]/text()").toString();
        if(id == null) {
            //TODO error 日志
            return;
        }
        String targetUrl = CrawlerConstants.SHENGFUCANG_DATA_URL + id;
        page.addTargetRequest(targetUrl);
    }

    public void processNowMatchTerm(Page page){
        page.setSkip(true);
        String data = page.getJson().get();
        JSONObject obj = (JSONObject) ((JSONArray) JSON.parse(data)).get(0);
        JSONArray tremList = obj.getJSONArray("tremList");
        String term = obj.getString("ctrem"); //当前期数
        String targetUrl = CrawlerConstants.SHENGFUCANG_NOW_URL.replace("qishu",term);
        page.addTargetRequest(targetUrl);
        int index = tremList.indexOf(term);
        if(index>0){
            String nextTerm = (String) tremList.get(index-1);
            targetUrl = CrawlerConstants.SHENGFUCANG_NOW_URL.replace("qishu",nextTerm);
            page.addTargetRequest(targetUrl);
        }
    }

    public void processMatch(Page page) {
//        page.setSkip(true);  //不需要传到pipeline
        String data = page.getJson().get();
        JSONObject obj = (JSONObject) ((JSONArray) JSON.parse(data)).get(0);
        LotteryNumber model = new LotteryNumber();
        JSONObject lterm = obj.getJSONObject("lterm");
        model.setTerm(lterm.getString("term"));
        String openTime_fmt = lterm.getString("openTime_fmt");
        model.setDate(openTime_fmt);
//        model.setDetails(obj.getString("match_vs"));
        model.setCreated_time((int) (System.currentTimeMillis()/1000L));
        model.setStart_sale(lterm.getString("sTime"));
        model.setEnd_sale(lterm.getString("fTime"));
        model.setType(4);
        JSONArray array =  obj.getJSONArray("match_vs");
        //关联赔率
        for(int i=0;i<array.size();i++){
            JSONObject match = (JSONObject) array.get(i);
            String homeTeamView = match.getString("homeTeamView");
            String awayTeamView = match.getString("awayTeamView");
            String matchname = match.getString("matchname");
            String matchTime = match.getString("matchTime");
            Map map = new HashMap();
//            map.put("first_team",homeTeamView);
//            map.put("second_team",awayTeamView);
            map.put("match_type",matchname);
            map.put("date",matchTime.replace("月","-").replace("日",""));
            String sfcTeamInfo = homeTeamView+awayTeamView; //胜负彩球队信息
           List<LotteryFootball> footballList =  mapper.selectDetailsForSfc(map);
            int countP =0;
            String plDetail ="";
            String jczqMatchTime = "";
           for(LotteryFootball lotteryFootball :footballList){
                String firstTeam = lotteryFootball.getFirst_team();
                String secondTeam = lotteryFootball.getSecond_team();
                String jczqTeamInfo = firstTeam+secondTeam; //竞彩足球球队信息
               int count = 0;
               for(int m=0;m<sfcTeamInfo.length();m++){
                   if(jczqTeamInfo.contains(String.valueOf(sfcTeamInfo.charAt(m)))){
                       count++;
                   }
               }
               if(count>countP&&count>3) {
                   countP = count;
                   plDetail = lotteryFootball.getDetails();
                   jczqMatchTime = lotteryFootball.getDate();
               }
           }
            JSONObject plJson = JSONObject.parseObject(plDetail);
            if(plJson!=null) {
                plJson.getString("detail2");
                match.put("sheng", plJson.getJSONObject("detail2").getString("胜"));
                match.put("ping", plJson.getJSONObject("detail2").getString("平"));
                match.put("fu", plJson.getJSONObject("detail2").getString("负"));
                match.put("matchTime", jczqMatchTime);
            }else{
                match.put("sheng", "");
                match.put("ping", "");
                match.put("fu", "");
                match.put("matchTime", jczqMatchTime);
            }
        }
        model.setDetails(array.toString());
        System.out.println("-------------------------");
        page.putField("model", model);
    }
}
